package com.sjtfreaks.jet.movieapp.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.sjtfreaks.jet.movieapp.Bean.HotData;
import com.sjtfreaks.jet.movieapp.R;
import com.sjtfreaks.jet.movieapp.adapter.HotAdapter;
import com.sjtfreaks.jet.movieapp.utils.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jet on 2018-10-16.
 */

public class HotFragment extends Fragment{

    private ListView mListView;
    private List<HotData> mList = new ArrayList<>();

    public static HotFragment newInstance(String name){
        Bundle args = new Bundle();
        args.putString("name", name);
        HotFragment fragment = new HotFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hot,null);
        findView(view);
        return view;

    }

    private void findView(View view) {
        mListView = (ListView) view.findViewById(R.id.mListView);
        mList.clear();
        //port 警报
        String url = "https://api-m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=290";//时光电影
        RxVolley.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                //Toast.makeText(getActivity(),t, Toast.LENGTH_SHORT).show();
                parsingJson(t);
                L.i("json:"+t);
            }
        });
    }

    private void parsingJson(String t) {
        try {
            JSONObject jsonObject = new JSONObject(t);
            JSONArray jsonList = jsonObject.getJSONArray("movies");

            for (int i = 0; i<jsonList.length();i++){
                JSONObject json = (JSONObject) jsonList.get(i);
                HotData data = new HotData();

                String title = json.getString("titleCn");

                data.setTitleCn(json.getString("titleCn"));
                data.setRatingFinal(json.getString("ratingFinal"));
                data.setCommonSpecial(json.getString("commonSpecial"));
                data.setType(json.getString("type"));
                data.setImg(json.getString("img"));
                mList.add(data);
            }
            HotAdapter adapter = new HotAdapter(getActivity(),mList);
            mListView.setAdapter(adapter);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}
